package com.cy.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Component;

import com.cy.entity.BackPurview;
import com.cy.entity.NormalStatus;

@Component("backPurviewDao")
public class BackPurviewDao extends BaseDAOHibernate<BackPurview>{
	
	public BackPurview saveBackPurview(BackPurview backPurview){
		this.getHibernateTemplate().save(backPurview);
		return backPurview;
	}
	
	public List<BackPurview> listBackPurview(String sortTree,int level){
		List<BackPurview> backPurviews=new ArrayList<BackPurview>();
		Session session=this.getSession();
		StringBuffer hql=new StringBuffer();
		hql.append(" FROM BackPurview bp WHERE bp.level=:level AND bp.sortTree=:sortTree AND bp.status=:status");
		Query query =session.createQuery(hql.toString());
		query.setParameter("level", level);
		query.setParameter("sortTree", sortTree);
		query.setParameter("status", NormalStatus.NORMAL);
		backPurviews= query.list();
		return backPurviews;
		
	}
	
	public List<BackPurview> listBackPurviewByLevel(Integer level) {
		List<BackPurview> backPurviews=new ArrayList<BackPurview>();
		Session session=this.getSession();
		StringBuffer hql=new StringBuffer();
		hql.append(" FROM BackPurview bp WHERE bp.level=:level AND bp.status=:status ORDER BY bp.sortNo ");
		Query query =session.createQuery(hql.toString());
		query.setParameter("level", level);
		query.setParameter("status", NormalStatus.NORMAL);
		return query.list();
	}
	
	public List<BackPurview> listBackPurviewByParent(Long parentId){
		Session session=this.getSession();
		StringBuffer hql=new StringBuffer();
		if(parentId!=null){
			hql.append("FROM BackPurview bp WHERE bp.parent.id=:parentId and bp.status=:status ORDER BY bp.sortNo");
			Query query =session.createQuery(hql.toString());
			query.setParameter("status", NormalStatus.NORMAL);
			query.setParameter("parentId", parentId);
			return query.list();
		}else{
			
		}
		return null;
	}
	
	public void delBackPurviewDWR(Long id, boolean isParent) {
		if(isParent){
			List<BackPurview> backPurviews=listBackPurviewByParent(id);
			for(BackPurview backPurview:backPurviews){
				backPurview.setStatus(NormalStatus.DELETE);
			}
			BackPurview parentBp=this.getObject(BackPurview.class, id);
			parentBp.setStatus(NormalStatus.DELETE);
		}else{
			BackPurview parentBp=this.getObject(BackPurview.class, id);
			parentBp.setStatus(NormalStatus.DELETE);
		}
	}

	public List<BackPurview> listAllPurviewForSysAdmin() {
		Session session=this.getSession();
		StringBuffer hql=new StringBuffer();
		hql.append("FROM BackPurview bp WHERE bp.status=:status ORDER BY bp.sortTree");
		Query query=session.createQuery(hql.toString());
		query.setParameter("status", NormalStatus.NORMAL);
		return query.list();
	}
	
}
